package com.example.springbootmaster.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootmaster.model.User;
import com.example.springbootmaster.service.UserService;
import com.example.springbootmaster.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Action;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.springbootmaster.annotation.UserConstant.USER_LOGIN_STATE;

/**
* @author 13109
 * 用户服务实现类
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-01-08 16:46:20
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;
    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yh";



    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {

        //1, 校验
       if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword))
       {
           return -1;
       }
       if(userAccount.length()<4||userAccount.length()>16){
           return -1;
       }
       if(userPassword.length()<8 || checkPassword.length()<8){
           return -1;
       }

        //.账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            return -1;
        }
//        密码和校验密码相同
        if(!userPassword.equals(checkPassword)){
            return -1;
        }
        //.账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if(count>0){
            return -1;
        }
        //2.加密

        String s = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //3.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(s);
        boolean save = this.save(user);

        if(!save){
            return -1;
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        //1, 校验
        if(StringUtils.isAnyBlank(userAccount,userPassword))
        {
            //todo 修改为自定义异常
            return null;
        }
        if(userAccount.length()<4||userAccount.length()>16){
            return null;
        }

        //.账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            return null;
        }


        //2.加密
        String s = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        /**
         * 查询用户是否存在
         */
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",s);
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
            log.info("user not exist  用户或密码错误");
            return null;
        }
        //用户脱敏
        User safetyUser = getSafetyUser(user);
      //记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }
    /**
     * 用户脱敏
     * @param user
     * @return
     */
    @Override
    public User getSafetyUser(User user){
        //用户脱敏
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setUnionId(user.getUnionId());
        safetyUser.setMpOpenId(user.getMpOpenId());
        safetyUser.setUserName(user.getUserName());
        safetyUser.setUserAvatar(user.getUserAvatar());
        safetyUser.setUserProfile(user.getUserProfile());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setEditTime(user.getEditTime());
        safetyUser.setCreateTime(user.getCreateTime());
        return safetyUser;
    }


}




